package com.leyou.service;

import ch.qos.logback.classic.Logger;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import com.leyou.entity.Cart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.service
 * @date 2019/7/11 21:28
 * @description:
 **/
@Service
@Slf4j
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String KEY_PREFIX = "ly:cart:uid";

    public void addCart(Cart cart) {

        //获取用户Id，用来绑定用户信息
        String key = KEY_PREFIX + UserHolder.getUser();

        //准备将用户的购物车信息存到Redis中，以用户Id为key，skuId为filter，剩下的信息为value
        //构建Redis中存贮结构
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        addCartInRedis(cart, hashOps);

    }

    private void addCartInRedis(Cart cart, BoundHashOperations<String, String, String> hashOps) {
        //先获得原有cart中的信息
        //获得skuId
        String skuId = cart.getSkuId().toString();

        //获得原有商品的添加数量
        int num = cart.getNum();

        //判断购物车中是否有添加的商品，若有修改数据
        if (hashOps.hasKey(skuId)) {
            //商品以前已经添加过了，将商品的value封装到cast对象中
            cart = JsonUtils.toBean(hashOps.get(skuId), Cart.class);
            //更新商品添加数量
            cart.setNum(num + cart.getNum());
        }
        //若没有，将数据回写到Redis中
        hashOps.put(skuId, JsonUtils.toString(cart));
    }


    public List<Cart> queryCart() {

        //判断购物车是否存在
        String key = KEY_PREFIX + UserHolder.getUser();
        Boolean boo = redisTemplate.hasKey(key);
        if (boo == null || !boo) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //判断是否存在数据
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        Long size = hashOps.size();
        if (size == null || size < 0) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //获取商品数据
        List<String> list = hashOps.values();

        //返回购物车的商品数据
        return list.stream().map(s -> JsonUtils.toBean(s, Cart.class)).collect(Collectors.toList());
    }


    public void updateGoodsNum(Long skuId, Integer num) {

        //获取用户
        String key = KEY_PREFIX + UserHolder.getUser();

        //查询查询商品是否存在
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        String hasKey = skuId.toString();
        Boolean boo = hashOps.hasKey(hasKey);
        if (boo == null || !boo) {
            log.error("购物车商品不存在！，用户是：{}，商品是：{}",UserHolder.getUser(),skuId);
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        //修改商品的数量
        Cart cart = JsonUtils.toBean(hashOps.get(hasKey), Cart.class);
        cart.setNum(num);
        //回写redis
        hashOps.put(hasKey,JsonUtils.toString(cart));

    }


    public void deleteGoods(Long skuId) {

        //获取用户信息
        String key =KEY_PREFIX+UserHolder.getUser();

        redisTemplate.opsForHash().delete(key,skuId.toString());

    }


    public void addCartList(List<Cart> carts) {
        //获取用户信息
        String key =KEY_PREFIX+UserHolder.getUser();

        //获取hash操作的对象，并绑定用户id
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        for (Cart cart : carts) {
            addCartInRedis(cart,hashOps);
        }

    }
}
